import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/home/authorize_bean.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/checkin/checkinmodel.dart';
import 'package:opene/ui/manage/adjust/adjustmodel.dart';
import 'package:opene/utils/ImageUtils.dart';
import 'package:toast/toast.dart';

class ReTallySubmitScreen extends StatelessWidget {
  ReTally reTally;

  ReTallySubmitScreen({this.reTally});

  @override
  Widget build(BuildContext context) {
    return ReTallySubmitScreenPage(reTally: reTally);
  }
}

class ReTallySubmitScreenPage extends StatefulWidget {
  ReTally reTally;

  ReTallySubmitScreenPage({this.reTally});

  @override
  _ReTallySubmitScreenPageState createState() => _ReTallySubmitScreenPageState(reTally: reTally);
}

class _ReTallySubmitScreenPageState extends BaseState<ReTallySubmitScreenPage> {
  ReTally reTally;

  _ReTallySubmitScreenPageState({this.reTally});

  final TextEditingController ctnEditingController = TextEditingController();
  final TextEditingController pcsEditingController = TextEditingController();
  bool layoutPcs = false;

  int index = 0, position, ctn = 0, pcs = 0;

  PhotoBean lengthPhoto = new PhotoBean();
  PhotoBean widthPhoto = new PhotoBean();
  PhotoBean heightPhoto = new PhotoBean();
  PhotoBean weightPhoto = new PhotoBean();

  @override
  String setTitle({String title}) {
    return "Re-Tally: Submit";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    next = "Submit";
    if (!Utils.isEmpty(reTally.upType) && (reTally.upType == "PCS")) {
      layoutPcs = true;
    }

    ctnFocusNode.requestFocus();
  }

  @override
  void dispose() {
    ctnFocusNode.dispose(); // 不要忘记销毁FocusNode
    pcsFocusNode.dispose(); // 不要忘记销毁FocusNode
    super.dispose();
  }

  FocusNode ctnFocusNode = FocusNode();
  FocusNode pcsFocusNode = FocusNode();

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(
                "IBLPN: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Expanded(
                child: Text(
                  Utils.getStringisEmpty(reTally.lpn),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Text(
                "Container: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Expanded(
                child: Text(
                  Utils.getStringisEmpty(reTally.containerNo),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          Row(
            children: [
              Text(
                "SKU: ",
                style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
              ),
              Expanded(
                child: Text(
                  Utils.getStringisEmpty(reTally.sku),
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                ),
              ),
            ],
          ),
          SizedBox(height: 5,),
          Row(
            children: [
              Container(
                width: 60,
                child: Text(
                  "Quantity: ",
                  style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                ),
              ),
              Expanded(
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    maxLines: 1,
                    controller: ctnEditingController,
                    keyboardType: TextInputType.number,
                    textInputAction: TextInputAction.next,
                    onSubmitted: (String text) {
                      if (layoutPcs) {
                        pcsFocusNode.requestFocus();
                      }
                    },
                    // autofocus: true,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        padding: EdgeInsets.all(2.0),
                        icon: Icon(
                          Icons.remove_circle_outline,
                          size: 30,
                          color: MyAppTheme.nearlyBlue,
                        ),
                        onPressed: () {
                          setState(() {
                            print("ctnonPressed");
                            if(Utils.isEmpty(ctnEditingController.text)){
                              return;
                            }
                            if(!Utils.isInteger(ctnEditingController.text)){
                              return;
                            }
                            ctn = int.parse(ctnEditingController.text);
                            if (ctn == 0) {
                              return;
                            }
                            ctn--;
                            ctnEditingController.text = "${ctn}";
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: MyAppTheme.nearlyBlue,
                        ),
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点之外的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点时的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      filled: true,
                      fillColor: MyAppTheme.white,
                      //隐藏下划线
                      //border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                    ),
                  ),
                ),
              ),
            ],
          ),
          Visibility(
              visible: layoutPcs,
              child: Container(
                margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
                child: Row(
                  children: [
                    Container(
                      width: 60,
                      child: Text(
                        "PCS: ",
                        style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                      ),
                    ),
                    Expanded(
                        child: ConstrainedBox(
                      constraints: BoxConstraints(maxHeight: 35),
                      child: TextField(
                        focusNode: pcsFocusNode,
                        controller: pcsEditingController,
                        keyboardType: TextInputType.number,
                        textInputAction: TextInputAction.next,
                        onSubmitted: (String text) {},
                        // autofocus: true,
                        decoration: InputDecoration(
                          suffixIcon: IconButton(
                            padding: EdgeInsets.all(2.0),
                            icon: Icon(
                              Icons.remove_circle_outline,
                              size: 30,
                              color: MyAppTheme.nearlyBlue,
                            ),
                            onPressed: () {
                              setState(() {
                                if(Utils.isEmpty(pcsEditingController.text)){
                                  return;
                                }
                                if(!Utils.isInteger(pcsEditingController.text)){
                                  return;
                                }
                                pcs = int.parse(pcsEditingController.text);
                                if (pcs == 0) {
                                  return;
                                }
                                pcs--;
                                pcsEditingController.text = "${pcs}";
                              });
                            },
                          ),
                          border: OutlineInputBorder(
                            borderSide: BorderSide(
                              color: MyAppTheme.nearlyBlue,
                            ),
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点之外的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                            // 设置焦点时的边框颜色
                            borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                          ),
                          filled: true,
                          fillColor: MyAppTheme.white,
                          //隐藏下划线
                          //border: InputBorder.none,
                          hintStyle: TextStyle(color: Colors.grey),
                          contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                        ),
                      ),
                    )),
                  ],
                ),
              )),
          Expanded(
            flex: 1, //设置权重
            child: SingleChildScrollView(
              child: Column(
                children: [
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: setPhotoView("length:  ", 0, lengthPhoto),
                      ),
                      Expanded(
                        flex: 1,
                        child: setPhotoView("width:  ", 1, widthPhoto),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: setPhotoView("height:  ", 2, heightPhoto),
                      ),
                      Expanded(
                        flex: 1,
                        child: setPhotoView("weight:  ", 3, weightPhoto),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Container setPhotoView(String hintText, int type, PhotoBean photoBean) {
    return Container(
      margin: const EdgeInsets.only(left: 0, top: 10, right: 0, bottom: 0),
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 1, //设置权重
            child: Container(
              height: 70,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    '*',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                  ),
                  Text(
                    hintText,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 12.0),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            flex: 2, //设置权重
            child: Row(
              children: [
                Container(
                  width: 70,
                  height: 70,
                  child: Stack(
                    children: <Widget>[
                      GestureDetector(
                        onTap: () {
                          // 请求焦点
                          FocusScope.of(context).requestFocus(FocusNode());
                          index = type;
                          ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? pickImages(context) : imgFileDialog(photoBean, Constants.baseImgUrl);
                        },
                        child: photoBean.image == null
                            ? (photoBean.urlImg == null
                                ? Image.asset(
                                    'assets/images/add.png',
                                    width: 70,
                                    height: 70,
                                    fit: BoxFit.cover,
                                  )
                                : Image.network(
                                    Constants.baseImgUrl + photoBean.urlImg,
                                    width: 70,
                                    height: 70,
                                    fit: BoxFit.cover,
                                  ))
                            : Image.file(
                                photoBean.image,
                                width: 70,
                                height: 70,
                                fit: BoxFit.cover,
                              ),
                      ),
                      Visibility(
                        visible: ((photoBean.image == null) && Utils.isEmpty(photoBean.urlImg)) ? false : true,
                        child: Positioned(
                          top: 2.0,
                          right: 2.0,
                          child: GestureDetector(
                            onTap: () {
                              setState(() {
                                photoBean.urlImg = null;
                                photoBean.image = null;
                              });
                            },
                            child: Image.asset(
                              'assets/images/ic_delete_menu.png',
                              width: 15,
                              height: 15,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  flex: 2, //设置权重
                  child: Text(
                    '',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.red, fontSize: 12.0),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Future pickImages(context) async {
    File image = await ImageUtils.chosePhotoOnAlbumOrCamera(context: context);
    print(image.path);
    String name = "";
    setState(() {
      switch (index) {
        case 0:
          lengthPhoto.image = image;
          name = "photo1";
          break;
        case 1:
          widthPhoto.image = image;
          name = "photo2";
          break;
        case 2:
          heightPhoto.image = image;
          name = "photo3";
          break;
        case 3:
          weightPhoto.image = image;
          name = "photo4";
          break;
      }
      fileUpload(reTally.containerNo, "retally", image, name, index, position, false, false);
      print("index:${index},position:${position}");
      print(image.path);
    });
  }

  @override
  void setNext() {
    if(Utils.isEmpty(ctnEditingController.text)){
      ctn=0;
    }else if(!Utils.isInteger(ctnEditingController.text)){
      ctn=0;
    }else{
      ctn = int.parse(ctnEditingController.text);
    }

    if(Utils.isEmpty(pcsEditingController.text)){
      pcs=0;
    }else if(!Utils.isInteger(pcsEditingController.text)){
      pcs=0;
    }else{
      pcs = int.parse(pcsEditingController.text);
    }

    setSubmit();
  }

  ReTallyQr reTallyQr = new ReTallyQr();

  void setSubmit() {
    ToastContext().init(context);
    if (Utils.isEmpty(reTally.upType) || (reTally.upType == "CTN")) {
      // if (ctn < 1) {
      //   Toast.show("please input quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      //   return;
      // }

      if (ctn > 0) {
        if ((lengthPhoto.image == null) && (lengthPhoto.urlImg == null)) {
          Toast.show("Please add photo1 photo", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
        if ((widthPhoto.image == null) && (widthPhoto.urlImg == null)) {
          Toast.show("Please add photo2 photo", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
        if ((heightPhoto.image == null) && (heightPhoto.urlImg == null)) {
          Toast.show("Please add photo3 photo", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
        if ((weightPhoto.image == null) && (weightPhoto.urlImg == null)) {
          Toast.show("Please add photo4 photo", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
      }
      reTallyQr.ctnQty = ctn;
      reTallyQr.reTallyQty = ctn;
      reTallyQr.pcsQty=0;
    } else if (reTally.upType == "PCS") {
      // if (ctn < 1) {
      //   Toast.show("please input quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      //   return;
      // }
      // if (pcs < 1) {
      //   Toast.show("please input pcs", duration: Toast.lengthShort, gravity: Toast.bottom);
      //   return;
      // }
      if (ctn > pcs) {
        Toast.show("PCS need be equal or greater than CTN", duration: Toast.lengthShort, gravity: Toast.bottom);
        return;
      }

      if (ctn > 0||pcs>0) {
        if ((lengthPhoto.image == null) && (lengthPhoto.urlImg == null)) {
          Toast.show("Please add photo1 photo", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
        if ((widthPhoto.image == null) && (widthPhoto.urlImg == null)) {
          Toast.show("Please add photo2 photo", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
        if ((heightPhoto.image == null) && (heightPhoto.urlImg == null)) {
          Toast.show("Please add photo3 photo", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
        if ((weightPhoto.image == null) && (weightPhoto.urlImg == null)) {
          Toast.show("Please add photo4 photo", duration: Toast.lengthShort, gravity: Toast.bottom);
          return;
        }
      }

      reTallyQr.ctnQty = ctn;
      reTallyQr.pcsQty = pcs;
      reTallyQr.reTallyQty = pcs;
    }
    if (DateTime.now().millisecondsSinceEpoch - timeMillis < 1000) {
      return;
    }
    timeMillis = DateTime.now().millisecondsSinceEpoch;

    if (Utils.isEmpty(lengthPhoto.urlImg)) {
      fileUpload(reTally.containerNo, "retally", lengthPhoto.image, "photo1", 0, position, true, true);
      return;
    }
    if (Utils.isEmpty(widthPhoto.urlImg)) {
      fileUpload(reTally.containerNo, "retally", widthPhoto.image, "photo2", 1, position, true, true);
      return;
    }
    if (Utils.isEmpty(heightPhoto.urlImg)) {
      fileUpload(reTally.containerNo, "retally", heightPhoto.image, "photo3", 2, position, true, true);
      return;
    }
    if (Utils.isEmpty(weightPhoto.urlImg)) {
      fileUpload(reTally.containerNo, "retally", weightPhoto.image, "photo4", 3, position, true, true);
      return;
    }

    reTallyQr.lpn = reTally.lpn;
    reTallyQr.tallyTaskId = reTally.tallyTaskId;
    reTallyQr.notifyId = reTally.notifyId;
    reTallyQr.sku = reTally.sku;
    reTallyQr.location = reTally.lpn;

    reTallyQr.switchNotifyId = reTally.switchNotifyId;
    LpnPhotoReqVo lpnPhotoReqVo = new LpnPhotoReqVo();

    lpnPhotoReqVo.photo1 = lengthPhoto.urlImg;
    lpnPhotoReqVo.photo2 = widthPhoto.urlImg;
    lpnPhotoReqVo.photo3 = heightPhoto.urlImg;
    lpnPhotoReqVo.photo4 = weightPhoto.urlImg;
    reTallyQr.lpnPhotoReqVo = lpnPhotoReqVo;
    submit();
  }

  void submit() async {
    updateHint('');

    String url = Constants.reTally;
    int version = 0;
    try {
      if (Constants.jumpMapBean != null) {
        List<JumpBean> data = Constants.jumpMapBean.MANAGE_Adjustment.data;
        for (JumpBean jumpBean in data) {
          if (jumpBean.name == "ReTally") {
            version = jumpBean.version;
          }
        }
      }
    } catch (e) {
      e.printStackTrace();
    }
    if (version == 2) {
      url = Constants.reTally_v2_submit;
    }

    String json = jsonEncode(reTallyQr);
    // 显示加载中对话框
    LoadingIndicator.show(context, title: "Submit...");

    BaseResponse baseResponse = await NetworkManager().request(context, url, method: version == 2?BaseMethod.post:BaseMethod.put, data: json);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      Navigator.of(context).pop(true);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
    reset();
  }

  void reset() {
    setState(() {
      ctn = 0;
      pcs = 0;
      lengthPhoto = new PhotoBean();
      widthPhoto = new PhotoBean();
      heightPhoto = new PhotoBean();
      weightPhoto = new PhotoBean();
      ctnEditingController.text = "";
      pcsEditingController.text = "";
    });
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    switch (type) {
      case 0:
        lengthPhoto.urlImg = path;
        break;
      case 1:
        widthPhoto.urlImg = path;
        break;
      case 2:
        heightPhoto.urlImg = path;
        break;
      case 3:
        weightPhoto.urlImg = path;
        break;
    }

    if (isSubmit) {
      setSubmit();
    }
  }
}
